package online.xuping.center.ai;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.github.artbits.quickio.api.DB;
import com.github.artbits.quickio.core.QuickIO;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 类描述:    .
 *
 * @author xuping
 * 创建时间:  [2023/6/16 13:38]
 */

@Service
public class BaiduWenXinYiYanServiceImpl {
    private DB db;
    private final String token;
    private final BaiduTokenServiceImpl baiduTokenService;

    public BaiduWenXinYiYanServiceImpl() {
        BaiduTokenServiceImpl baiduTokenService = new BaiduTokenServiceImpl( );
        this.baiduTokenService = baiduTokenService;
        this.token = baiduTokenService.token();
        this.db=  QuickIO.usingDB(this.getClass().getName());
    }

    public BaiduWenXinYiYanServiceImpl(BaiduTokenServiceImpl baiduTokenService) {
        this.baiduTokenService = baiduTokenService;
        this.token = baiduTokenService.token();
        this.db=  QuickIO.usingDB(this.getClass().getName());
    }

    public void initMe(){

    }
    public static String getBody(String src) {
        return JSONUtil.toJsonStr(new AiChatDomain("user", src));
    }

    public String chat(String message) {
        String re = chat(message, "completions");
        AiChatDomain aiChatDomain = new AiChatDomain("user", message);
        aiChatDomain.setAnswer(re);
        this.db.collection(AiChatDomain.class).save(aiChatDomain);
        return aiChatDomain.getAnswer();
    }


    /**
     * 输出所有的信息
     * @return
     */
    public List<AiChatDomain> showChat( ) {
        return this.db.collection(AiChatDomain.class).findAll();
    }



    public String chat(String message, String algorithm) {
        try {
            String result2 =
                    HttpRequest.post("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/" + algorithm +
                                    "?access_token=" +
                                    token)
                            .header(Header.ACCEPT, "application/json")
                            .header(Header.CONTENT_TYPE, "application/json")
                            .body(getBody(message))
                            .timeout(20000)
                            .execute().body();
            return JSONUtil.parseObj(result2).getStr("result");

        } catch (Exception e) {
            throw BaiduErrorCodeEnum.SERVICE_ERROR.exception();
        }
    }
}
